<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2019/12/20
// +----------------------------------------------------------------------

namespace app\common\services;

use app\common\constants\ApiConstant;
use app\common\facade\Arr;
use app\common\facade\Help;
use app\common\facade\TransItem;
use think\Db;

/**
 *
 * Class MarketService
 * @package app\common\services
 * @author feraner<feraner@163.com>
 * @date 2019/12/20
 */
class MarketService
{


    /**
     * 二手商品详情
     * @param       $id
     * @param array $need
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsDetail($id, $need = [])
    {

        $result = Db::name('market')->alias('m')
            ->where('m.id', $id)
            ->join('market_type mt', 'mt.id = m.tid')
            ->field('m.*,mt.name as marketTypeName,mt.img as marketTypeImg')
            ->find() ?: [];

        //二手商品内容表
        if (in_array('content', $need)) {
            $result['extendContent'] = Db::name('market_extend')
                ->where('market_id', Arr::get($result, 'id', 0))
                ->find() ?: [];
        }
        //发布兼职的人
        if (in_array('publishUser', $need) && Arr::get($result, 'user_id')) {
            $result['extendPublishUser'] = Db::name('user')->alias('u')
                ->where('u.id', Arr::get($result, 'user_id'))
                ->join('user_extend ue', 'u.id = ue.user_id')
                ->field('u.id,u.name,u.truename,u.avatar,ue.publish_job_num')
                ->find() ?: [];
        }

        $result['statusCh'] = TransItem::transMarketGoodsStatus(Arr::get($result, 'status'));
        $result['publishTimeCh'] = date('Y年m月d日 H时i分', Arr::get($result, 'created_at'));
        $result['imageArr'] = array_filter(explode('|', Arr::get($result, 'image')));
        $result['ignoreMobile'] = Help::ignoreMobile(Arr::get($result, 'mobile'));

        return $result;


    }


    /**
     * 二手商品列表
     * @param       $where
     * @param       $page
     * @param       $pageSize
     * @param array $need
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsList($where, $page, $pageSize, $need = [])
    {
        $goodsDb = Db::name('market')->alias('m');

        //是否上架
        if ($isShow = Arr::get($where, 'isShow')) {
            $goodsDb->where('m.is_show', $isShow);
        }

        //状态
        if(Arr::get($where, 'status')) {
            $goodsDb->where('m.status', Arr::get($where, 'status'));
        } else {
            $goodsDb->where('m.status', 3);
        }

        //二手商品类型
        if ($marketType = Arr::get($where, 'marketType')) {
            $goodsDb->where('m.tid', $marketType);
        }
        //地区
        if ($provincesId = Arr::get($where, 'provincesId')) {
            $goodsDb->where('m.provinces_id', $provincesId);
        }
        if ($cityId = Arr::get($where, 'cityId')) {
            $goodsDb->where('m.city_id', $cityId);
        }
        if ($countyId = Arr::get($where, 'countyId')) {
            $goodsDb->where('m.county_id', $countyId);
        }

        //发布人
        if ($publishId = Arr::get($where, 'publishUserId')) {
            $goodsDb->where('m.publish_id', $publishId);
        }

        //根据goodsId来获取
        if ($goodsIdArr = Arr::get($where, 'goodsIdArr')) {
            $goodsDb->where('m.id', 'IN', $goodsIdArr);
        }

        //根据 兼职标题 获取
        if ($searchName = Arr::get($where, 'searchName', '')) {
            $goodsDb->where('m.name', 'LIKE', '%' . $searchName . '%');
        }


        $goodsList = $goodsDb->join('market_type mt', 'mt.id = m.tid')
            ->field('mt.name as marketTypeName, mt.img as marketTypeImg')
            ->field('m.*')
            ->order('m.updated_at DESC,m.collect_num DESC,m.top DESC')
            ->page($page, $pageSize)
            ->select() ?: [];

        foreach ($goodsList as &$item) {
            $item['publishTimeCh'] = date('Y年m月d日', Arr::get($item, 'updated_at'));
            $item['statusCh'] = TransItem::transMarketGoodsStatus(Arr::get($item, 'status'));
        }

        return $goodsList;
    }


    /**
     * 删除二手商品
     * @param $goodsInfo
     * @param $publishId
     *
     * @return bool
     * @throws \Exception
     */
    public function deleteGoods($goodsInfo, $publishId)
    {
        try {
            Db::startTrans();

            $result = Db::name('market')
                ->where('id', Arr::get($goodsInfo, 'id'))
                ->where('publish_id', $publishId)
                ->update([
                    'updated_at'        => time(),
                    'is_show'           => 0,
                ]);
            if ($result) {
                /*
                $result = Db::name('market_extend')
                    ->where('market_id', Arr::get($goodsInfo, 'id'))
                    ->delete() ?: false;
                if (!$result) {
                    throw new \Exception(
                        ApiConstant::MARKET_DELETE_GOODS_EXTEND_ERROR_STR,
                        ApiConstant::MARKET_DELETE_GOODS_EXTEND_ERROR
                    );
                }
                */
                Db::commit();
            } else {
                throw new \Exception(
                    ApiConstant::MARKET_DELETE_GOODS_ERROR_STR,
                    ApiConstant::MARKET_DELETE_GOODS_ERROR
                );
            }
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }

        return $result;
    }




}
